package com.baizhi.controller;


import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.baizhi.util.ImageCodeUtil;
import com.baizhi.vo.CommonVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

@CrossOrigin   //处理跨域
@RestController
@RequestMapping("admin")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    @Resource
    AdminService adminService;

    @PostMapping("getImageCodes")
    public String getImageCodes(HttpServletRequest request){
        //1.获取验证码随机字符
        String code = ImageCodeUtil.getSecurityCode();
        log.info("验证码为：{}",code);
        //2.存储验证码随机字符
        request.getServletContext().setAttribute("code",code);

        String imgBase64 =null;
        try {

            //3.生成验证码图片转为Base64的格式
            imgBase64 = ImageCodeUtil.careateImgBase64(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgBase64;
    }

    @PostMapping("login")
    public HashMap<String, Object> login(@RequestBody Admin admin, String enCode){
        log.info("admin {}",admin);
        log.info("接收用户的验证码是：{}",enCode);

        HashMap<String, Object> map = adminService.login(admin, enCode);

        return map;
    }

    @PostMapping("logout")
    public void logout(HttpServletRequest request){
        log.info("退出登录");

        //移除登陆标记
        request.getServletContext().removeAttribute("admin");

    }

    @RequestMapping("queryAllPage")
    public HashMap<String,Object> queryAllPage(Integer page,Integer pageSize){
        log.info("当前页：{}",page);
        log.info("每页展示条数：{}",pageSize);

        HashMap<String, Object> map = adminService.queryAllpage(page, pageSize);

        return map;
    }


    @RequestMapping("update")
    public HashMap<String,Object> update(@RequestBody Admin admin){

        log.info("修改用户数据：{}",admin);

        HashMap<String, Object> map = adminService.update(admin);

        return map;
    }

    @RequestMapping("delete")
    public HashMap<String,Object> delete(@RequestBody Admin admin){

        log.info("删除用户数据：{}",admin);

        HashMap<String, Object> map = adminService.delete(admin);

        return map;
    }

    @RequestMapping("add")
    public CommonVo add(@RequestBody Admin admin){

        log.info("添加用户数据：{}",admin);


        return adminService.add(admin);
    }

    @RequestMapping("queryById")
    public Admin queryById(String id){

        log.info("查询用户数据：{}",id);


        return adminService.queryById(id);
    }



}
